#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include <unistd.h>

#define LEFT 	30000000
#define RIGHT 	30000200
#define THRNUM 	4

//参数结构体
struct thr_arg_st
{
	int n;
};

//全局变量num
static int num = 0;
//初始化互斥锁
static pthread_mutex_t mutex_num = PTHREAD_MUTEX_INITIALIZER;

//线程处理函数
static void * the_primer(void * p)
{
	int i;
	int j;
	while(1)
	{
		pthread_mutex_lock(&mutex_num);			//上锁
		while(num == 0)							//查询num状态
		{
			pthread_mutex_unlock(&mutex_num);	//解锁
			sched_yield();						//调度
			pthread_mutex_lock(&mutex_num);		//上锁
		}
		if(num == -1)
		{
			pthread_mutex_unlock(&mutex_num);
			break;//注意临界区内的所有跳转！！！！！！！
		}
		i = num;								//取值
		num = 0;								//写〇
		pthread_mutex_unlock(&mutex_num);		//解锁

		int mark = 1;
		for(j = 2; j < i / 2; j ++)
		{
			if(i % j == 0)
				{
					mark = 0;
					break;
				}
		}
		if(mark == 1)
			printf("[%d]:%d is a primer\n", ((struct thr_arg_st *)p)->n, i);
	}
	pthread_exit(NULL);
}

int main()
{
	int i, err;
	pthread_t tid[THRNUM];
	struct thr_arg_st * p;
	void * ptr_to_free;

	for(i = 0; i < THRNUM; i++)
	{
		//为参数申请空间
		p = malloc(sizeof(*p));
		if(p == NULL)
		{
			perror("malloc");
			exit(1);
		}
		//为参数赋值
		p->n = i;
		//创建线程
		err = pthread_create(&tid[i], NULL, the_primer, p);
		if(err)
		{
			fprintf(stderr, "create:%s", strerror(err));
			exit(1);
		}
	}
	//分发任务
	for(i = LEFT; i < RIGHT; i ++)
	{
		pthread_mutex_lock(&mutex_num);
		while(num != 0)
		{
			pthread_mutex_unlock(&mutex_num);
			sched_yield();//调度给到别人
			pthread_mutex_lock(&mutex_num);
		}
		num = i;
		pthread_mutex_unlock(&mutex_num);
	}
	//发布下班信息
	pthread_mutex_lock(&mutex_num);
	while(num != 0)
	{
		pthread_mutex_unlock(&mutex_num);
		sched_yield();//调度给到别人
		pthread_mutex_lock(&mutex_num);
	}
	num = -1;
	pthread_mutex_unlock(&mutex_num);
	//回收线程
	for(i = 0; i < THRNUM; i++)
	{
		pthread_join(tid[i], &ptr_to_free);
		free(ptr_to_free);
	}
	//销毁互斥锁
	pthread_mutex_destroy(&mutex_num);

	exit(0);
}